#!/usr/bin/env python3
import json
import csv
from datetime import datetime

# Read JSON data
with open('bill_data.json', 'r') as f:
    data = json.load(f)

# Prepare CSV data
csv_rows = []

# Process daily costs
for daily_cost in data['daily_costs']:
    date = daily_cost['date']
    timestamp = daily_cost['timestamp']

    # Process each line item for that day
    for item in daily_cost['line_items']:
        row = {
            'Date': date,
            'Timestamp': timestamp,
            'Model': item['name'],
            'Cost': item['cost'],
            'Requests': item['usage']['model_stats']['Requests'],
            'Prompt_Tokens': item['usage']['model_stats']['Prompt'],
            'Completion_Tokens': item['usage']['model_stats']['Completion'],
            'Reasoning_Tokens': item['usage']['model_stats']['Reasoning'],
            'Total_Tokens': item['usage']['model_stats']['Prompt'] + item['usage']['model_stats']['Completion'],
            'Credit_Used': item['usage']['model_stats']['CreditUsed'],
            'Request_Percentage': item['usage']['usage_analysis']['request_percentage'],
            'Cost_Percentage': item['usage']['usage_analysis']['cost_percentage']
        }
        csv_rows.append(row)

# Write to CSV
output_file = 'bill_data.csv'
if csv_rows:
    with open(output_file, 'w', newline='', encoding='utf-8') as f:
        fieldnames = csv_rows[0].keys()
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(csv_rows)

    print(f"CSV file saved as: {output_file}")
    print(f"Total rows: {len(csv_rows)}")
else:
    print("No data to save")

# Also create a summary CSV with daily totals
summary_rows = []
for daily_cost in data['daily_costs']:
    summary_row = {
        'Date': daily_cost['date'],
        'Total_Requests': daily_cost['total_requests'],
        'Total_Prompt_Tokens': daily_cost['total_prompt'],
        'Total_Completion_Tokens': daily_cost['total_completion'],
        'Total_Reasoning_Tokens': daily_cost['total_reasoning'],
        'Total_Credit_Used': daily_cost['total_credit_used'],
        'Request_Percentage': daily_cost['usage_analysis']['request_percentage'],
        'Cost_Percentage': daily_cost['usage_analysis']['cost_percentage']
    }
    summary_rows.append(summary_row)

# Write summary to CSV
summary_file = 'bill_summary.csv'
if summary_rows:
    with open(summary_file, 'w', newline='', encoding='utf-8') as f:
        fieldnames = summary_rows[0].keys()
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(summary_rows)

    print(f"Summary CSV saved as: {summary_file}")
    print(f"Total days: {len(summary_rows)}")

# Create user-based CSV
user_rows = []
if 'usage_users' in data and data['usage_users']:
    for user in data['usage_users']:
        user_row = {
            'User_ID': user['id'],
            'User_Name': user['name'],
            'User_Email': user['email'],
            'Total_Requests': user['total_requests'],
            'Total_Prompt_Tokens': user['total_prompt'],
            'Total_Completion_Tokens': user['total_completion'],
            'Total_Reasoning_Tokens': user['total_reasoning'],
            'Total_Tokens': user['total_prompt'] + user['total_completion'],
            'Total_Credit_Used': user['total_credit_used'],
            'Total_Images': user['total_image_n'],
            'Request_Percentage': user['usage_analysis']['request_percentage'],
            'Cost_Percentage': user['usage_analysis']['cost_percentage']
        }
        user_rows.append(user_row)

    # Sort by total requests descending
    user_rows.sort(key=lambda x: x['Total_Requests'], reverse=True)

# Write user data to CSV
user_file = 'bill_by_user.csv'
if user_rows:
    with open(user_file, 'w', newline='', encoding='utf-8') as f:
        fieldnames = user_rows[0].keys()
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(user_rows)

    print(f"User-based CSV saved as: {user_file}")
    print(f"Total users: {len(user_rows)}")

    # Print top 5 users by requests
    print("\nTop 5 users by request count:")
    for i, user in enumerate(user_rows[:5], 1):
        print(f"{i}. {user['User_Name']}: {user['Total_Requests']} requests ({user['Request_Percentage']:.2f}%)")